package org.ww.msm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.ww.commonutils.R;
import org.ww.msm.service.MsmService;
import org.ww.msm.utils.RandomUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/service/msm")
//@CrossOrigin
public class MsmController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private MsmService msmService;

    @GetMapping("/send/{phone}")
    public R send(@PathVariable String phone){
        //1 先在redis中获取用户code，如果存在（未过期），返回成功
        String code = (String) redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //2 获取不到用户code，发送短信
        //生成四位随机验证码
        code = RandomUtil.getFourBitRandom();
        //将验证码存入map中
        Map<String,Object> map=new HashMap<>();
        map.put("code",code);
        boolean flag=msmService.send(map,phone);

        if(flag){
            //成功之后将验证码存入redis中
            //设置过期时间5分钟
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);

            return R.ok();
        }else{
            return R.error().message("短信发送失败!");
        }
    }
}
